
<script setup>import { ref, computed, onMounted, onUnmounted } from 'vue'
import { useUserStore } from '../stores/user.js'
import { showSuccessToast, showFailToast } from 'vant'
import router from '../router/router.js'
import { getCurrentInstance } from 'vue'

const userStore = useUserStore()
const { proxy } = getCurrentInstance()

// 表单数据 - 提供默认值避免渲染时出错
const formData = ref({
  username: '',
  phone: '',
  gender: 0,
  birth_date: '',
  avatar: ''
})

// 控制各个弹窗的显示
const showModal = ref({
  username: false,
  phone: false,
  gender: false,
  birthDate: false,
  avatar: false
})

// 手机号修改相关
const newPhone = ref('')
const phoneCode = ref('')
const isCountingDown = ref(false)
const countdown = ref(60)
let timer = null

// 性别选项
const genderOptions = [
  { text: '未知', value: 0},
  { text: '男', value: 1 },
  { text: '女', value: 2 }
]

// 用于性别选择器的值（必须是数组）
const genderPickerValue = ref([0])

// 出生日期选择器的值（必须是数组）
const birthDateValue = ref(['2000', '01', '01'])

// 从store获取用户信息
const userInfo = computed(() => userStore.userInfo)

// 返回上一页
const goBack = () => {
  router.go(-1)
}

// 页面加载时初始化表单数据
onMounted(() => {
  formData.value = {
    username: userInfo.value.username || '',
    phone: userInfo.value.phone || '',
    gender: userInfo.value.gender || 0,
    birth_date: userInfo.value.birth_date || '',
    avatar: userInfo.value.avatar || ''
  }

  // 初始化选择器的值
  genderPickerValue.value = [formData.value.gender]

  // 初始化出生日期选择器的值
  if (formData.value.birth_date) {
    birthDateValue.value = formData.value.birth_date.split('-')
  }
})

// 倒计时文本
const countdownText = computed(() => {
  return isCountingDown.value ? `${countdown.value}秒后重新发送` : '发送验证码'
})

// 打开头像修改弹窗
const openAvatarModal = () => {
  showModal.value.avatar = true
}

// 打开修改用户名弹窗
const openUsernameModal = () => {
  showModal.value.username = true
}

// 打开修改手机号弹窗
const openPhoneModal = () => {
  showModal.value.phone = true
  newPhone.value = formData.value.phone
  phoneCode.value = ''
}

// 打开修改性别弹窗
const openGenderModal = () => {
  showModal.value.gender = true
  genderPickerValue.value = [formData.value.gender] // 同步当前值
}

// 打开修改出生日期弹窗
const openBirthDateModal = () => {
  showModal.value.birthDate = true
  if (formData.value.birth_date) {
    birthDateValue.value = formData.value.birth_date.split('-')
  }
}

// 统一的用户信息更新API调用
const updateUserInfo = (updateData) => {
  // 构建完整的用户数据对象
  const userData = {
    user_id: userInfo.value.user_id, // 添加用户ID
    username: formData.value.username,
    phone: formData.value.phone,
    gender: formData.value.gender,
    birth_date: formData.value.birth_date,
    ...updateData // 合并要更新的特定字段
  }

  return proxy.$axios.put('/user/updateUser', userData)
      .then(response => {
        if (response.data.code === 0) {
          // 更新store中的用户信息
          userStore.setUserInfo({
            ...userInfo.value,
            ...updateData
          })
          showSuccessToast('信息更新成功')
          return Promise.resolve(response.data)
        } else {
          showFailToast(response.data.msg || '更新失败')
          return Promise.reject(response.data)
        }
      })
      .catch(error => {
        console.error('更新失败', error)
        // 更详细的错误处理
        if (error.response) {
          // 服务器返回了错误响应
          showFailToast(error.response.data.msg || '更新失败，请稍后重试')
        } else if (error.request) {
          // 请求已发出但没有收到响应
          showFailToast('网络错误，请检查网络连接')
        } else {
          // 其他错误
          showFailToast('更新失败，请稍后重试')
        }
        return Promise.reject(error)
      })
}

// 上传头像
const onAvatarUpload = (event) => {
  const file = event.target.files[0]
  if (!file) return

  // 检查文件类型
  if (!file.type.startsWith('image/')) {
    showFailToast('请选择图片文件')
    return
  }

  // 检查文件大小 (限制为2MB)
  if (file.size > 2 * 1024 * 1024) {
    showFailToast('图片大小不能超过2MB')
    return
  }

  // 创建 FormData 对象用于文件上传
  const uploadData = new FormData()
  uploadData.append('file', file)
  uploadData.append('user_id', userInfo.value.user_id) // 添加用户ID

  // 上传图片到服务器
  proxy.$axios.post('/upload/file', uploadData, {
    headers: {
      'Content-Type': 'multipart/form-data'
    }
  }).then(response => {
    if (response.data.code === 0) {
      // 获取服务器返回的图片URL
      const avatarUrl = response.data.data
      // 更新用户信息
      updateUserInfo({ avatar: avatarUrl })
          .then(() => {
            formData.value.avatar = avatarUrl
            showModal.value.avatar = false
          })
          .catch(() => {
            // 错误处理已在updateUserInfo中完成
          })
    } else {
      showFailToast(response.data.msg || '上传失败')
    }
  }).catch(error => {
    console.error('上传失败', error)
    showFailToast('上传失败，请稍后重试')
  })
}

// 保存用户名
const saveUsername = () => {
  if (!formData.value.username.trim()) {
    showFailToast('请输入用户名')
    return
  }

  // 调用统一的更新API
  updateUserInfo({ username: formData.value.username })
      .then(() => {
        showModal.value.username = false
      })
      .catch(() => {
        // 错误处理已在updateUserInfo中完成
      })
}

// 发送验证码
const sendCode = () => {
  if (!newPhone.value) {
    showFailToast('请输入新手机号')
    return
  }
  if (newPhone.value === formData.value.phone) {
    showFailToast('新手机号不能与原手机号相同')
    return
  }
  if (newPhone.value.length !== 11) {
    showFailToast('请输入正确的11位手机号')
    return
  }


  proxy.$axios.post('/user/sendCode', {
    phone: newPhone.value
  }).then(ServerData => {
    if (ServerData.data.code === 0) {
      showSuccessToast("验证码发送成功")
      console.log(ServerData.data.data)
      startCountdown()
    } else {
      showFailToast(ServerData.data.msg || "验证码发送失败")
    }
  }).catch(error => {
    console.log("请求发生异常", error)
    showFailToast("验证码发送失败,请稍后重试")
  })
}

// 确认修改手机号
const confirmChangePhone = () => {
  if (!newPhone.value) {
    showFailToast('请输入新手机号')
    return
  }
  if (newPhone.value === formData.value.phone) {
    showFailToast('新手机号不能与原手机号相同')
    return
  }
  if (!phoneCode.value) {
    showFailToast('请输入验证码')
    return
  }

  // 调用修改手机号的专用API（需要验证码验证）
  proxy.$axios.put('/user/changePhone', {
    user_id: userInfo.value.user_id,
    phone: newPhone.value,
    code: parseInt(phoneCode.value) // 确保code是整数类型
  }).then(ServerData => {
    if (ServerData.data.code === 1) {
      // 更新store中的手机号
      userStore.setUserInfo({
        ...userInfo.value,
        phone: newPhone.value
      })
      formData.value.phone = newPhone.value
      showSuccessToast('手机号修改成功')
      showModal.value.phone = false
    } else{
      showFailToast(ServerData.data.msg)
    }
  }).catch(error => {
    console.log("请求发生异常", error)
    showFailToast("手机号修改失败,请稍后重试")
  })
}

// 保存性别
const saveGender = () => {
  // 从选择器数组中获取值
  const selectedGender = genderPickerValue.value[0]

  // 调用统一的更新API
  updateUserInfo({ gender: selectedGender })
      .then(() => {
        formData.value.gender = selectedGender
        showModal.value.gender = false
      })
      .catch(() => {
        // 错误处理已在updateUserInfo中完成
      })
}

// 保存出生日期
const saveBirthDate = () => {
  // 从选择器数组中构建日期字符串
  const selectedBirthDate = birthDateValue.value.join('-')

  // 调用统一的更新API
  updateUserInfo({ birth_date: selectedBirthDate })
      .then(() => {
        formData.value.birth_date = selectedBirthDate
        showModal.value.birthDate = false
      })
      .catch(() => {
        // 错误处理已在updateUserInfo中完成
      })
}

// 退出登录
const logout = () => {
  userStore.$reset()
  showSuccessToast('已退出登录')
  router.push('/login')
}

// 开始倒计时
const startCountdown = () => {
  isCountingDown.value = true
  countdown.value = 60

  timer = setInterval(() => {
    countdown.value--
    if (countdown.value <= 0) {
      stopCountdown()
    }
  }, 1000)
}

// 停止倒计时
const stopCountdown = () => {
  isCountingDown.value = false
  clearInterval(timer)
  timer = null
}

// 组件卸载时清除定时器
onUnmounted(() => {
  if (timer) {
    clearInterval(timer)
  }
})
</script>

<template>
  <div class="edit-user-info">
    <div class="header">
      <van-icon name="arrow-left" class="back-icon" @click="goBack" />
      <h3>个人信息</h3>
    </div>

    <van-cell-group style="margin-top: 20px">
      <!-- 头像 -->
      <van-cell title="头像" is-link @click="openAvatarModal">
        <template #default>
          <van-image
              round
              width="40px"
              height="40px"
              :src="formData.avatar || 'https://img.yzcdn.cn/vant/cat.jpeg'"
              fit="cover"
          />
        </template>
      </van-cell>

      <!-- 用户名 -->
      <van-cell title="用户名" :value="formData.username || '未设置'" is-link @click="openUsernameModal" />

      <!-- 手机号 -->
      <van-cell title="手机号" :value="formData.phone" is-link @click="openPhoneModal" />

      <!-- 性别 -->
      <van-cell title="性别" :value="genderOptions.find(item => item.value === formData.gender)?.text || '未知'" is-link @click="openGenderModal" />

      <!-- 出生日期 -->
      <van-cell title="出生日期" :value="formData.birth_date || '未设置'" is-link @click="openBirthDateModal" />
    </van-cell-group>

    <div style="display: flex; justify-content: center; margin-top: 20px">
      <van-button
          type="default"          style="border-radius: 20px; width: 260px"
          @click="logout"
      >
        退出登录
      </van-button>
    </div>

    <!-- 修改头像弹窗 -->
    <van-dialog
        v-model:show="showModal.avatar"
        title="修改头像"
        show-cancel-button
        :show-confirm-button="false"
    >
      <div style="padding: 20px; text-align: center;">
        <van-image
            round
            width="100px"
            height="100px"
            :src="formData.avatar || 'https://img.yzcdn.cn/vant/cat.jpeg'"
            fit="cover"            style="margin-bottom: 20px;"
        />
        <input
            type="file"
            accept="image/*"
            @change="onAvatarUpload"            style="display: none;"
            ref="avatarInput"
        />
        <van-button
            type="primary"
            block
            @click="$refs.avatarInput.click()"
        >
          选择图片
        </van-button>
        <p style="font-size: 12px; color: #999; margin-top: 10px;">
          支持JPG、PNG格式，大小不超过2MB
        </p>
      </div>
    </van-dialog>

    <!-- 修改用户名弹窗 -->
    <van-dialog
        v-model:show="showModal.username"
        title="修改用户名"
        show-cancel-button
        @confirm="saveUsername"
    >
      <van-field
          v-model="formData.username"
          label="用户名"
          placeholder="请输入用户名"
      />
    </van-dialog>

    <!-- 修改手机号弹窗 -->
    <van-dialog
        v-model:show="showModal.phone"
        title="修改手机号"
        show-cancel-button
        @confirm="confirmChangePhone"
    >
      <van-cell-group>
        <van-field
            v-model="newPhone"
            label="新手机号"
            placeholder="请输入新手机号"
            type="tel"
        />
        <van-field
            v-model="phoneCode"
            label="验证码"
            placeholder="请输入验证码"
        >
          <template #button>
            <van-button
                size="small"
                type="primary"
                :disabled="isCountingDown"
                @click="sendCode"
            >
              {{ countdownText }}
            </van-button>
          </template>
        </van-field>
      </van-cell-group>
    </van-dialog>

    <!-- 修改性别弹窗 -->
    <van-popup v-model:show="showModal.gender" position="bottom">
      <van-picker
          :columns="genderOptions"
          v-model="genderPickerValue"
          @confirm="saveGender"
          @cancel="showModal.gender = false"
          show-toolbar
          title="选择性别"
      />
    </van-popup>

    <!-- 修改出生日期弹窗 -->
    <van-popup v-model:show="showModal.birthDate" position="bottom">
      <van-date-picker
          v-model="birthDateValue"
          @confirm="saveBirthDate"
          @cancel="showModal.birthDate = false"
          show-toolbar
          title="选择出生日期"
      />
    </van-popup>
  </div>
</template>

<style scoped>.edit-user-info {
  padding-bottom: 20px;
}

.header {
  margin-top: 10px;
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
  padding: 0 16px;
}

.back-icon {
  position: absolute;
  left: 16px;
  font-size: 24px;
  color: #333;
}

h3 {
  margin: 0;
}
</style>